﻿using System;
using System.Collections.Generic;
using ZyGames.DZPocker.Model;
using ZyGames.Framework.Game.Contract;
using ZyGames.DZPocker.Bll.Logic;
using ZyGames.Framework.Common.Serialization;
using ZyGames.DZPocker.Tools;

namespace ZyGames.DZPocker.Script.CsScript.Action
{
	/// <summary>
	/// 获得好友牌桌列表
	/// </summary>
	public class Action30076 : BaseAction
	{
		private string friendsIdStr;
		private string _friendsTableDataStr;
		private string _friendsSimpleUserDataStr;
		public Action30076(HttpGet actionGetter)
			: base((short)ActionType.DZGetFriendsTableInfo, actionGetter)
		{
		}
		public override bool GetUrlElement()
		{
			if (httpGet.GetString("FriendsIdStr", ref friendsIdStr))
			{
				return true;
			}
			return false;
		}

		public override bool TakeAction()
		{
			var friendsIds = ProtoBufUtils.Deserialize<List<int>>(Convert.FromBase64String(friendsIdStr));
			if(friendsIds.Count <= 0)
			{
				Tool.WriteErrorLine("消息30076获得的好友列表数量是0");
				return false;
			}
			var _friendsTableData = new List<UserPlayingTable>();
			var friendsUserData = new List<SimpleUserData>();
			foreach(var id in friendsIds)
			{
				var user = GameTable.Current.GetUser(id);
				if(user != null)
				{
					var tableIds = user.Property.TableIdList;
					if(tableIds.Count > 0)
					{
						foreach(var tableId in tableIds)
						{
							var table = GameRoom.Current.GetTableData(tableId);
							if(table != null)
							{
								var leftTime = table.GetLeftTime();
								var userPlayTable = new UserPlayingTable() { TableID = table.TableId, LeftTime = leftTime, TableName = table.TableName, UserHeadIcon = user.HeadIcon, UserNickName = user.NickName, UserId = id, Sign = user.Sign, Sex = user.Sex};
								if (!_friendsTableData.Contains(userPlayTable))
								{
									_friendsTableData.Add(userPlayTable);
									break;
								}
							}
						}
					}
					else
					{
						friendsUserData.Add(new SimpleUserData() { HeadIcon = user.HeadIcon, NickName = user.NickName, UserId = user.UserId });
					}
				}
			}

			_friendsTableDataStr = Convert.ToBase64String(ProtoBufUtils.Serialize(_friendsTableData));
			_friendsSimpleUserDataStr = Convert.ToBase64String(ProtoBufUtils.Serialize(friendsUserData));
			return true;
		}

		public override void BuildPacket()
		{
			this.PushIntoStack(this._friendsTableDataStr);
			this.PushIntoStack(this._friendsSimpleUserDataStr);
		}
	}
}
